<template>
    <div>
        <div v-if="sn">
            <div id="all_map" :style="'height:' + (!polyline?'85vh;':'81.5vh;')"></div>
            <!--<div id="r-result">-->
            <!--<input type="button" @click="add_control();" value="添加1"/>-->
            <!--<input type="button" @click="delete_control();" value="删除2"/>-->
            <!--</div>-->
            <div id="time_ctl_box">
                <div class="date_box" :style="'display:'+(polyline? 'flex' : 'none')">
                    <!--data-lcalendar="2010-01-11,2016-05-29"-->
                    <div class="time_input_box pos_r flex">
                        <input class="pos_r" id="start_time" type="text" readonly="" name="input_date"
                               placeholder="开始时间" v-model="start_time"/>
                        <img class="input_img pos_a"
                             src="http://weixin.pbani.com/wx/static/images/device_map/start_time.svg">
                    </div>

                    <span class="flex">&nbsp;&nbsp;&nbsp;~&nbsp;&nbsp;&nbsp;</span>

                    <div class="time_input_box pos_r">
                        <input class="pos_r" id="end_time" type="text" readonly="" name="input_date" placeholder="结束时间"
                               v-model="end_time"/>
                        <img class="input_img pos_a"
                             src="http://weixin.pbani.com/wx/static/images/device_map/end_time.svg">
                    </div>

                    <img class="flex" style="width:5vh;transform: translateX(1vh)" @click="close_polyline"
                         src="http://weixin.pbani.com/wx/static/images/device_map/location.svg">
                </div>
                <div class="btn_box" :style="'display:'+(!polyline? 'block' : 'none')">
                    <img style="height:100%;" @click="open_polyline"
                         src="http://weixin.pbani.com/wx/static/images/device_map/polyline.svg">
                </div>
            </div>
        </div>
        <div v-else>
            请先绑定设备，然后可以进行定位!!
        </div>
    </div>
</template>
<script>
    import {http} from "../../static/js/common";

    export default {
        props: ['sn', 'geoc', 'device'],
        data() {
            return {
                polyline: false,
                map: null,
                infoWindow: null,
                zoom: 14,
                _center: null,
                marker: null,
                circle: null,
                points_markers: null,
                intervals: [],
                polyline_arr: [],
                start_time: "",
                end_time: "",
                last_point_info: null,
                way_point: {
                    markers: [],
                    lineArr: [],
                }
            }
        },
        watch: {
            device(val, oldVal) {
                console.log('oldVal');
                console.log(oldVal);
                console.log('newval');
                console.log(val);
                this.location()
                this.l()
            },
            start_time(val, oldVal) {
                this.search_polyline();
            },
            end_time(val, oldVal) {
                this.search_polyline();
            }
        },
        methods: {
            waypoint_paint: function (arr) {//[{time:,point[lon,lat]},{},{}]
                this.map.clearMap();

                if (!arr) {
                    return;
                }

                this.way_point.markers = [];
                this.way_point.lineArr = [];

                for (var i = 0; i < arr.length; i++) {
                    var val = arr[i];
                    var marker = new AMap.Marker({
                        icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
                        position: [val['point'][1], val['point'][0]]
                    });
                    this.way_point.markers.push(marker);
                    this.way_point.lineArr.push([val['point'][1], val['point'][0]]);
                    this.map.add(marker);
                }

                var polyline = new AMap.Polyline({
                    path: this.way_point.lineArr,
                    isOutline: true,
                    outlineColor: '#ffeeff',
                    borderWeight: 1,
                    strokeColor: "#3366FF",
                    strokeOpacity: 1,
                    strokeWeight: 2,
                    // 折线样式还支持 'dashed'
                    strokeStyle: "solid",
                    // strokeStyle是dashed时有效
                    strokeDasharray: [10, 5],
                    lineJoin: 'round',
                    lineCap: 'round',
                    zIndex: 50,
                })

                polyline.setMap(this.map)
                // 缩放地图到合适的视野级别
                this.map.setFitView([polyline])


                // this.way_point.markers = [];
                // this.way_point.lineArr = [];
                //
                // for (var i = 0; i < arr.length; i++) {
                //     var val = arr[i];
                //     var point = new BMap.Point(val['point'][1], val['point'][0]);
                //     var marker = new BMap.Marker(point);//设置marker
                //     this.map.addOverlay(marker);
                //
                //     this.way_point.markers.push(marker);
                //     this.way_point.lineArr.push(point);
                // }
                //
                // if (this.way_point.lineArr.length > 1) {
                //     var polyline = new BMap.Polyline(this.way_point.lineArr
                //         , {strokeColor: "blue", strokeWeight: 2, strokeOpacity: 0.5});
                //     this.map.addOverlay(polyline);
                // }
                //
                // this.map.centerAndZoom(point, 15);
            },
            close_polyline() {
                this.polyline = false;
                this.map.clearMap();//清除地图
                this.center = this.last_point_info;
            },
            open_polyline() {
                this.polyline = true;
                this.search_polyline();
            },
            add_control() {

            },
            delete_control() {

            },
            location() {
                if (this.polyline) {
                    return;
                }
                if (!this.device) {
                    return;
                }
                let device_type;
                if (this.device.hasOwnProperty('type')) {
                    device_type = this.device['type']
                } else {
                    device_type = 0
                }

                http({
                    url: "get_points",
                    param: {
                        'device_type': device_type,
                        'sn': this.sn,
                        'limit': 1
                    }
                }).then(data => {
                    console.log(data.list.length);
                    if (data.list.length <= 0) {
                        return
                    }
                    let item = data.list[0];
                    // $.alert(`${item.point[1]}, ${item.point[0]}`);
                    this.center = [item.point[1], item.point[0]];
                });
            },
            l() {
                if (this.polyline) {
                    return;
                }
                if (!this.device) {
                    return;
                }
                let device_type;
                if (this.device.hasOwnProperty('type')) {
                    device_type = this.device['type']
                } else {
                    device_type = 0
                }
                http({
                    url: "location",
                    param: {
                        'device_type': device_type,
                        'sn': this.sn
                    }
                }).then(data => {
                });
            },
            initMap() {
                this.location();
                this.l();

                this.map = new AMap.Map('all_map', {
                    resizeEnable: true, //是否监控地图容器尺寸变化
                    zoom: 15, //初始化地图层级
                    center: [113.89658356, 22.53500748] //初始化地图中心点
                });
                let toolBar = new AMap.ToolBar({
                    visible: true
                });
                this.map.addControl(toolBar);
            },
            init_calendar() {
                let calendardatetime_start = new lCalendar();
                calendardatetime_start.init({
                    'trigger': '#start_time',
                    'type': 'datetime'
                });

                let calendardatetime_end = new lCalendar();
                calendardatetime_end.init({
                    'trigger': '#end_time',
                    'type': 'datetime'
                });

                setTimeout(() => {
                    this.start_time = (new Date(new Date().toLocaleDateString())).format('yyyy-MM-dd hh:mm');
                    this.end_time = (new Date()).format('yyyy-MM-dd hh:mm');
                }, 1000);

            },
            search_polyline() {
                if (!this.polyline) {
                    return;
                }
                if (!this.device) {
                    return;
                }

                this.center = null;

                let device_type;
                if (this.device.hasOwnProperty('type')) {
                    device_type = this.device['type']
                } else {
                    device_type = 0
                }

                console.log('search')
                console.log(this.start_time)
                console.log(this.end_time)

                http({
                    url: "get_points",
                    param: {
                        'device_type': device_type,
                        'sn': this.sn,
                        'start_time': this.start_time || 0,
                        'end_time': this.end_time || 0,
                        'limit': 1000
                    }
                }).then(data => {
                    this.waypoint_paint(data.list);
                });
            },
            afterCenter() {
                this.map.panTo([parseFloat(this.last_point_info[0]), parseFloat(this.last_point_info[1])]);

                this.marker = new AMap.Marker({
                    icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
                    position: [parseFloat(this.last_point_info[0]), parseFloat(this.last_point_info[1])]
                });
                this.map.add(this.marker);
                console.log('add marker');

                this.circle = new AMap.Circle({
                    center: new AMap.LngLat(this.last_point_info[0], this.last_point_info[1]), // 圆心位置
                    radius: this.last_point_info[2] || 300,  //半径
                    strokeColor: "blue",  //线颜色
                    strokeOpacity: 1,  //线透明度
                    strokeWeight: 1,  //线粗细度
                    fillColor: "blue",  //填充颜色
                    fillOpacity: 0.1 //填充透明度
                });
                this.map.add(this.circle);
                console.log('add circle');

                this.map.clearInfoWindow();

                var info = [];
                info.push("<div class='input-card content-window-card'><div><img style=\"float:left;\" src=\" https://webapi.amap.com/images/autonavi.png \"/></div> ");
                info.push("<div style=\"padding:7px 0px 0px 0px;\"><h4>高德软件</h4>");
                info.push("<p class='input-item'>电话 : 010-84107000   邮编 : 100102</p>");
                info.push("<p class='input-item'>地址 :北京市朝阳区望京阜荣街10号首开广场4层</p></div></div>");


                this.infoWindow = new AMap.InfoWindow({
                    content: info.join(""),  //使用默认信息窗体框样式，显示信息内容
                    offset: new AMap.Pixel(1, -30),  //使用默认信息窗体框样式，显示信息内容
                });

                // //关闭信息窗体
                // function closeInfoWindow() {
                //     map.clearInfoWindow();
                // }

                AMap.event.addListener(this.marker, 'click', () => {
                    //构建信息窗体中显示的内容
                    this.infoWindow.open(this.map, this.marker.getPosition());
                });

                // this.geoc.getLocation(new BMap.Point(point_info[0], point_info[1]), (rs) => {
                //     //addressComponents对象可以获取到详细的地址信息
                //     let addComp = rs.addressComponents;
                //     let site = addComp.city + addComp.district + addComp.street + addComp.streetNumber;
                //     if (!site) {
                //         site = "未知区域"
                //     }
                //     //地址获取成功后增加点击坐标的信息窗口
                //     let opts = {
                //         width: 250, // 信息窗口宽度
                //         height: 80, // 信息窗口高度
                //         title: "地理位置", // 信息窗口标题
                //         enableMessage: true
                //         // 设置允许信息窗发送短息
                //     };
                //     let infoWindow = new BMap.InfoWindow(site, opts);  // 创建信息窗口对象
                //     this.marker.addEventListener("click", function () {
                //         this.map.openInfoWindow(infoWindow, this._center); //开启信息窗口
                //     });
                // });
            }
        },
        computed: {
            center: {
                set(point_info) {
                    if (this.marker) {
                        this.map.remove(this.marker);
                    }
                    if (this.circle) {
                        this.map.remove(this.circle);
                    }
                    if (point_info === null) {
                        return;
                    }

                    if (this.last_point_info === point_info) {
                        this.afterCenter()
                    } else {
                        let device_type;
                        if (this.device.hasOwnProperty('type')) {
                            device_type = this.device['type']
                        } else {
                            device_type = 0
                        }


//定义一些常量
                        let piObj = {
                            x_PI: 3.14159265358979324 * 3000.0 / 180.0,
                            PIs: 3.1415926535897932384626,
                            a: 6378245.0,
                            ee: 0.00669342162296594323
                        }

                        /**
                         * WGS84转GCj02
                         * @param lng
                         * @param lat
                         * @returns {*[]}
                         */
                        function wgsToGc(lng, lat) {
                            // let lnglat = retConfirmNum (lng, lat);
                            // lng = lnglat[0];
                            // lat = lnglat[1];
                            let dlat = transformlat(lng - 105.0, lat - 35.0);
                            let dlng = transformlng(lng - 105.0, lat - 35.0);
                            let radlat = lat / 180.0 * piObj.PIs;
                            let magic = Math.sin(radlat);
                            magic = 1 - piObj.ee * magic * magic;
                            let sqrtmagic = Math.sqrt(magic);
                            dlat = (dlat * 180.0) / ((piObj.a * (1 - piObj.ee)) / (magic * sqrtmagic) * piObj.PIs);
                            dlng = (dlng * 180.0) / (piObj.a / sqrtmagic * Math.cos(radlat) * piObj.PIs);
                            let mglat = lat + dlat;
                            let mglng = lng + dlng;
                            return [mglng, mglat];
                        }

                        function transformlat(lng, lat) {
                            let ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
                            ret += (20.0 * Math.sin(6.0 * lng * piObj.PIs) + 20.0 * Math.sin(2.0 * lng * piObj.PIs)) * 2.0 / 3.0;
                            ret += (20.0 * Math.sin(lat * piObj.PIs) + 40.0 * Math.sin(lat / 3.0 * piObj.PIs)) * 2.0 / 3.0;
                            ret += (160.0 * Math.sin(lat / 12.0 * piObj.PIs) + 320 * Math.sin(lat * piObj.PIs / 30.0)) * 2.0 / 3.0;
                            return ret
                        }

                        function transformlng(lng, lat) {
                            let ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
                            ret += (20.0 * Math.sin(6.0 * lng * piObj.PIs) + 20.0 * Math.sin(2.0 * lng * piObj.PIs)) * 2.0 / 3.0;
                            ret += (20.0 * Math.sin(lng * piObj.PIs) + 40.0 * Math.sin(lng / 3.0 * piObj.PIs)) * 2.0 / 3.0;
                            ret += (150.0 * Math.sin(lng / 12.0 * piObj.PIs) + 300.0 * Math.sin(lng / 30.0 * piObj.PIs)) * 2.0 / 3.0;
                            return ret
                        }


                        if (device_type == 0) {
                            AMap.convertFrom([point_info[0], point_info[1]], "baidu", (status, result) => {
                                this.last_point_info = [result.locations[0].lng, result.locations[0].lat]
                                this.afterCenter()
                            });
                        } else {
                            let lnglat = wgsToGc(point_info[0], point_info[1]); //WGS84转GCj02
                            this.last_point_info = [lnglat[0], lnglat[1]]
                            this.afterCenter()
                        }


                        // let data = [113.89650726, 22.53662109]
                        // console.log('yuan')
                        // console.log(data)
                        // AMap.convertFrom(data, "gps", (status, result) => {
                        //     console.log("gps")
                        //     console.log(result)
                        // });
                        // AMap.convertFrom(data, "mapbar", (status, result) => {
                        //     console.log("mapbar")
                        //     console.log(result)
                        // });
                        // AMap.convertFrom(data, "baidu", (status, result) => {
                        //     console.log("baidu")
                        //     console.log(result)
                        // });
                    }
                },
                get() {
                    return this._center;
                }
            }
        },
        created() {
            if (!this.sn) {
                this.$emit(
                    'state',
                    {
                        page: 'add_device'
                    }
                );
                return
            }

            console.log(this.sn);
            if (this.sn === "008796750258458") {
                setTimeout(() => {
                    this.center = [113.90482774196, 22.537452688256];
                }, 3000);
            }

            this.intervals.push(setInterval(() => {
                this.location();
            }, 30000));
        },
        beforeDestroy() {
            let tid;
            for (tid of this.intervals) {
                clearInterval(tid);
            }
        },
        mounted() {
            this.initMap();
            this.init_calendar();
        }
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
    #all_map {
        width: 100vw;
        overflow: hidden;
        margin: 0;
    }

    #time_ctl_box {
        position: absolute;
        width: 100vw;
        height: 10vh;
        overflow: hidden;
        top: 81.5vh;
        margin: 0;
        background-color: rgba(0, 0, 0, 0);
    }

    #time_ctl_box .date_box {
        background: white;
        position: relative;
        width: 100%;
        height: 100%;
        overflow: hidden;
        bottom: 0;
        justify-content: center;
        align-items: center;
    }

    #time_ctl_box .btn_box {
        background: white;
        position: absolute;
        width: 100%;
        height: 70%;
        overflow: hidden;
        bottom: 0;
        text-align: center;
    }

    .time_input_box {
        height: 55%;
        display: flex;
        width: 40%;
    }

    .time_input_box input {
        padding-left: 5vh;
        width: 100%;
        border: 1px solid #19b5ee;
        border-radius: 5px;
    }

    .input_img {
        width: 5vh;
        transform: translate(0.1vh, 0.2vh);
    }
</style>
